package com.qys.livesMall.navy.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.anchor.model.entity.H2Anchor;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.constants.AppUserConstant;
import com.qys.livesMall.app.user.model.entity.AppUserLevel;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.enums.UserTypeEnum;
import com.qys.livesMall.app.user.service.AppUserGoldAccountService;
import com.qys.livesMall.app.user.service.AppUserLevelService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.app.user.utils.PasswordUtil;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MD5Util;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.finance.util.BusinessNoUtil;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.navy.model.dto.*;
import com.qys.livesMall.shop.constants.ShopConstant;
import com.qys.livesMall.shop.enums.ShopBusinessTypeEnum;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.service.H2ShopBaseService;
import com.qys.livesMall.system.model.entity.H2SysConfig;
import com.qys.livesMall.system.service.IH2SysConfigService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @menu NavyUserServer
 * @date 2023/07/03 13:44
 */
@Slf4j
@Service
public class NavyUserServer {

    @Autowired
    IH2AppUserService appUserService;

    @Autowired
    H2ShopBaseService shopBaseService;

    @Autowired
    private H2AnchorService anchorService;

    @Autowired
    private MessageServer messageServer;

    @Autowired
    private AppUserGoldAccountService goldAccountService;

    @Autowired
    private FinanceBusinessService financeBusinessService;
    @Resource
    private AppUserLevelService userLevelService;

    @Resource
    private IH2SysConfigService sysConfigService;

    @Transactional(rollbackFor = Exception.class)
    public R add(AddNavy addNavy, String ip) {
        if (StringUtils.isEmpty(addNavy.getNames())) {
            addNavy.setNames(MD5Util.randomString(6));
        }
        List<String> names =new ArrayList<>();
        List<String> namesTemp = Arrays.stream(addNavy.getNames().split(",")).toList();
        names.addAll(namesTemp);
        int adNum = addNavy.getCount() - names.size();
        for (int i = 0; i < adNum; i++) {
            names.add(names.get(0) + i);
        }
        UserTypeEnum userType = UserTypeEnum.REGULAR_USERS;
        if (addNavy.getAddShop() != null && Objects.equals(addNavy.getAddShop(), Constants.YesNoInt.YES)) {
            userType = UserTypeEnum.STORE;
        }
        if (addNavy.getAddAnchor() != null && Objects.equals(addNavy.getAddAnchor(), Constants.YesNoInt.YES)) {
            if (userType.equals(UserTypeEnum.REGULAR_USERS)) {
                userType = UserTypeEnum.ANCHOR;
            } else {
                userType = UserTypeEnum.STORE_AND_ANCHOR;
            }
        }
        H2AppUser h2AppUser = appUserService.userSuperiorInfo(addNavy.getInvitationCode());
        UserTypeEnum finalUserType = userType;
        List<H2AppUser> users = new ArrayList<>();
        AppUserLevel level = userLevelService.getOne(Wrappers.<AppUserLevel>query().orderByAsc("level").last("LIMIT 1"));
        H2SysConfig h2SysConfig=sysConfigService.getConfigByKey("userDefaultTopImg");
        names.stream().forEach(u -> {
            H2AppUser appUser = new H2AppUser();
            appUser.setUserName(MD5Util.randomString(8));
            while (appUserService.checkUserNameExist(appUser.getUserName())) {
                appUser.setUserName(MD5Util.randomString(8));
            }
            String salt = RandomStringUtils.randomAlphanumeric(8);
            String encrypt = PasswordUtil.encrypt(appUser.getUserName(), appUser.getUserName(), salt);
            appUser.setSalt(salt);
            appUser.setPassword(encrypt);
            appUser.setNickName(u);
            appUser.setUserSysType(AppUserConstant.SysUserType.NAVY);
            appUser.setUserType(finalUserType.getCode());
            appUser.setCreateBy(SecurityUtils.getUsername());
            appUser.setCreateTime(LocalDateTime.now());
            appUser.setSuperior(Long.parseLong(h2AppUser.getId()));
            appUser.setSuperiorName(h2AppUser.getNickName());
            appUser.setSuperiorUsername(h2AppUser.getUserName());
            appUser.setStatus(0);
            if (null != h2SysConfig){
                appUser.setAvatar(h2SysConfig.getValue());
            }
            if (null != level) {
                appUser.setUserLevelId(Long.valueOf(level.getId()));
                appUser.setUserLevel(level.getName());
            }
            appUser.setUserRandomId(appUserService.getRandomId());
            users.add(appUser);
        });
        //用户落库
        appUserService.adds(users,ip);
        H2SysConfig shopSysConfig=sysConfigService.getConfigByKey("shopDefaultTopImg");
        //店铺创建
        if (userType.equals(UserTypeEnum.STORE) || userType.equals(UserTypeEnum.STORE_AND_ANCHOR)) {
            List<H2ShopBase> shopBases = new ArrayList<>();
            users.stream().forEach(user -> {
                H2ShopBase shop = new H2ShopBase();
                shop.setUserId(Long.valueOf(user.getId()));
                shop.setShopName(user.getNickName() + "的店铺");
                shop.setType(ShopConstant.ShopType.NAVY);
                shop.setCreateTime(LocalDateTime.now());
                shop.setApprovalTime(shop.getCreateTime());
                shop.setStatus(ShopConstant.ShopStatus.FREEZE_SHOP);
                shop.setApprovalStatus(ShopConstant.AuditStatus.AUDITED);
                if (null != shopSysConfig){
                    shop.setShopAvatarUrl(shopSysConfig.getValue());
                }
                shopBases.add(shop);
            });
            shopBaseService.addNavyShops(shopBases);
        }

        //主播创建
        if (userType.equals(UserTypeEnum.ANCHOR) || userType.equals(UserTypeEnum.STORE_AND_ANCHOR)) {

            List<H2Anchor> anchors = new ArrayList<>();
            users.stream().forEach(user -> {
                H2Anchor anchor = new H2Anchor();
                anchor.setUserId(Long.valueOf(user.getId()));
                anchor.setAnchorName(user.getNickName());
                anchor.setAnchorStatus(Constants.YesNoInt.NO);
                anchor.setApplyStatus(2);
                anchor.setIsDelete(Constants.YesNoInt.NO);
                anchors.add(anchor);
            });

            anchorService.addAnchors(anchors);
        }

        return R.ok();
    }

    public R editName(EditNavyUserName navyUserName) {
        if (CollectionUtils.isEmpty(navyUserName.getUserIds()) || StringUtils.isEmpty(navyUserName.getNames())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }

        List<String> names = Arrays.stream(navyUserName.getNames().split(",")).toList();
        int count = navyUserName.getUserIds().size() - names.size();
        if (count > 0) {
            navyUserName.setUserIds(navyUserName.getUserIds().subList(0, names.size()));
        } else if (count < 0) {
            names = names.subList(0, navyUserName.getUserIds().size());
        }

        List<H2AppUser> appUsers = new ArrayList<>();
        for (int i = 0; i < navyUserName.getUserIds().size(); i++) {
            H2AppUser user = new H2AppUser();
            user.setId(navyUserName.getUserIds().get(i));
            user.setNickName(names.get(i));
            user.setUpdateTime(LocalDateTime.now());
            appUsers.add(user);
        }
        appUserService.updateBatchById(appUsers);
        return R.ok();
    }

    public R editBalance(EditNavyUserBalance userBalance) {
        if (CollectionUtils.isEmpty(userBalance.getUserIds()) || userBalance.getAmount() == null) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        userBalance.getUserIds().stream().forEach(userId -> {
            FinancePayDTO payDTO = new FinancePayDTO();
            payDTO.setUserId(Long.valueOf(userId));
            payDTO.setAmountIncurred(userBalance.getAmount());
            if (Objects.equals(ShopBusinessTypeEnum.GIFT.getType(), userBalance.getCategory())) {
                payDTO.setBusinessNo(BusinessNoUtil.get(AccountBusinessTypeEnum.GIFT));
                payDTO.setBusinessType(AccountBusinessTypeEnum.GIFT);
            }else  if (Objects.equals(ShopBusinessTypeEnum.DEDUCT.getType(), userBalance.getCategory())){
                payDTO.setBusinessNo(BusinessNoUtil.get(AccountBusinessTypeEnum.DEDUCT));
                payDTO.setBusinessType(AccountBusinessTypeEnum.DEDUCT);
            }
            payDTO.setAmountIncurred(userBalance.getAmount());
            try {
                financeBusinessService.pay(payDTO);
            } catch (QysException qe) {
                log.info("修改水军余额错误：" + qe.getMessage());
            } catch (Exception e) {
                log.error("修改水军余额错误:" + e);
            }
        });
        return R.ok();
    }

    public R editGold(EditNavyUserGold userGold) {
        if (CollectionUtils.isEmpty(userGold.getUserIds()) || userGold.getGoldNumber() == null) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }

        userGold.getUserIds().stream().forEach(userId -> {
            try {
                goldAccountService.balanceExchangeGold(Long.valueOf(userId), userGold.getGoldNumber());
            } catch (QysException qe) {
                log.info("兑换水军金币错误：" + qe.getMessage());
            } catch (Exception e) {
                log.error("兑换水军金币错误:" + e);
            }
        });
        return R.ok();
    }

    public R editPics(EditNavyUserPic userPic) {
        if (CollectionUtils.isEmpty(userPic.getUserIds()) || CollectionUtils.isEmpty(userPic.getPics())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }

        int count = userPic.getUserIds().size() - userPic.getPics().size();
        if (count > 0) {
            userPic.setUserIds(userPic.getUserIds().subList(0, userPic.getPics().size()));
        } else if (count < 0) {
            userPic.setPics(userPic.getPics().subList(0, userPic.getUserIds().size()));
        }

        List<H2AppUser> appUsers = new ArrayList<>();
        for (int i = 0; i < userPic.getUserIds().size(); i++) {
            H2AppUser user = new H2AppUser();
            user.setId(userPic.getUserIds().get(i));
            user.setAvatar(userPic.getPics().get(i));
            user.setUpdateTime(LocalDateTime.now());
            appUsers.add(user);
        }
        appUserService.updateBatchById(appUsers);
        return R.ok();
    }

    public R openShop(List<Long> userIds) {
        //获取已经开过店的用户
        List<Long> existUserIds = shopBaseService.existShopByUserIds(userIds);
        if (!CollectionUtils.isEmpty(existUserIds)) {
            userIds.removeAll(existUserIds);
        }
        List<H2AppUser> users = appUserService.listByIds(userIds);
        if (users == null) {
            return R.ok();
        }
        H2SysConfig shopSysConfig=sysConfigService.getConfigByKey("shopDefaultTopImg");
        //店铺创建
        List<H2ShopBase> shopBases = new ArrayList<>();
        users.stream().forEach(user -> {
            H2ShopBase shop = new H2ShopBase();
            shop.setUserId(Long.valueOf(user.getId()));
            shop.setShopName(user.getNickName() + "的店铺");
            shop.setType(ShopConstant.ShopType.NAVY);
            shop.setCreateTime(LocalDateTime.now());
            shop.setApprovalTime(shop.getCreateTime());
            shop.setStatus(ShopConstant.ShopStatus.FREEZE_SHOP);
            shop.setApprovalStatus(ShopConstant.AuditStatus.AUDITED);
            if (null != shopSysConfig){
                shop.setShopAvatarUrl(shopSysConfig.getValue());
            }
            shopBases.add(shop);
        });
        shopBaseService.addNavyShops(shopBases);
        users.stream().forEach(user -> {
            appUserService.becomeShopkeeper(Long.valueOf(user.getId()));

        });
        return R.ok();
    }

    public R openAnchor(List<Long> userIds) {
        //获取已经成为主播的用户
        List<Long> existUserIds = anchorService.existAnchorByUserIds(userIds);
        if (!CollectionUtils.isEmpty(existUserIds)) {
            userIds.removeAll(existUserIds);
        }
        List<H2AppUser> users = appUserService.listByIds(userIds);
        if (users == null) {
            return R.ok();
        }
        List<H2Anchor> anchors = new ArrayList<>();
        users.stream().forEach(user -> {
            H2Anchor anchor = new H2Anchor();
            anchor.setUserId(Long.valueOf(user.getId()));
            anchor.setAnchorName(user.getNickName());
            anchor.setAnchorStatus(Constants.YesNoInt.YES);
            anchor.setIsDelete(Constants.YesNoInt.NO);
            anchors.add(anchor);
        });

        anchorService.addAnchors(anchors);
        users.stream().forEach(user -> {
            appUserService.becomeShopkeeper(Long.valueOf(user.getId()));

        });

        return R.ok();
    }

}

